import threading
import socket
import time

refuse_count = 0
connect_count = 0

connect_mutex = threading.Lock()

def server_run():
    def client_proc(client_socket, ip):
        client_socket.send("来了老弟".encode("gbk"))

        # connect_mutex.acquire()
        global connect_count
        connect_count += 1
        print("客户端连接数", connect_count, "拒绝连接数", refuse_count)
        # connect_mutex.release()

        while True:
            data = client_socket.recv(1024)

            if not data:
                print("客户端断开", ip)
                break
            # print(data.decode("gbk"))
            # client_socket.send("哈哈".encode("gbk"))
            # time.sleep(1)
        client_socket.close()

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(("", 8080))
    server.listen(1000)

    while True:
        client, ip_port = server.accept()
        client_thread = threading.Thread(target=client_proc, args=(client, ip_port))
        client_thread.start()


def client_run():
    def client_proc(index):
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client.connect(("192.168.22.29", 8080))
        except Exception:
            global refuse_count
            refuse_count += 1
            print("服务器拒绝连接:", refuse_count)
            client.close()
            return

        client.send(("我来了%d" % index).encode("gbk"))
        while True:
            data = client.recv(1024)
            if not data:
                break
            # print(data.decode("gbk"))
            # client.send(("我是客户端%d" % index).encode("gbk"))
            # time.sleep(1)
        client.close()

    for i in range(10000):
        t = threading.Thread(target=client_proc, args=(i,))
        t.start()


if __name__ == '__main__':
    server = threading.Thread(target=server_run)
    server.start()
    client = threading.Thread(target=client_run)
    client.start()

